package views.tags.facebook;

import groovy.lang.Closure;
import java.io.PrintWriter;
import java.util.Map;
import play.modules.facebook.FbGraph;
import play.templates.FastTags;
import play.templates.GroovyTemplate.ExecutableTemplate;

/**
 *
 * @author Eric Jacob
 */
@FastTags.Namespace("fbg")
public class FbGraphTags extends FastTags {

    public static void _script(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
        out.println("<div id='fb-root'></div>");
        out.println("<script src='http" + getSsl(args.get("ssl")) + "://connect.facebook.net/" + getLocale(args.get("locale")) + "/all.js'></script>");
        out.println("<script>");
        out.println("    FB.init({appId: '" + FbGraph.getAppId() + "', status: true, cookie: true, xfbml: true});");
        out.println("</script>");
    }

    public static void _scriptAsync(Map<?, ?> args, Closure body, PrintWriter out, ExecutableTemplate template, int fromLine) {
        out.println("<div id='fb-root'></div>");
        out.println("<script>");
        out.println("    window.fbAsyncInit = function() {");
        out.println("        FB.init({appId: '" + FbGraph.getAppId() + "', status: true, cookie: true, xfbml: true});");
        out.println("    };");
        out.println("    (function() {");
        out.println("        var e = document.createElement('script'); e.async = true;");
        out.println("        e.src = document.location.protocol + '//connect.facebook.net/" + getLocale(args.get("locale")) + "/all.js';");
        out.println("        document.getElementById('fb-root').appendChild(e);");
        out.println("    }())");
        out.println("</script>");
    }

    private static String getLocale(Object obj) {
        String locale = String.valueOf(obj);
        if (!locale.equals("null") && !locale.isEmpty()) {
            return locale;
        } else {
            return "en_US";
        }
    }

    private static String getSsl(Object obj) {
        String ssl = String.valueOf(obj);
        if (!ssl.equals("null") && ssl.equals("true")) {
            return "s";
        } else {
            return "";
        }
    }
}
